package kr.hkit.powerjava.chapter26.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import kr.hkit.powerjava.chapter26.DBProperties;

public class ConnectionFactory {
	private String driver;	//com.mysql.jdbc.DRIVER
	private String url;
	private String user;
	private String password;
	
	private static ConnectionFactory instance = new ConnectionFactory();
	
	public static Connection getConnection(){
		return instance.createConnection(); //외부에서는 이것만 보인다.
	}
	
	private ConnectionFactory(){	//외부에서 접근 불가
		loadProperties();
		
		try {
			Class.forName(driver);//이름을 통해서 클래스를 불러온다.
		} catch (ClassNotFoundException e) {
			System.err.printf("%s", "MySQL Driver not found");
			System.exit(-1);		//0이 정상종료
		}	
	}

	private Connection createConnection(){			//connection = java.sql
		Connection con = null;
		try {
			con = DriverManager.getConnection(url, user, password);
			System.out.println("MySQL Connection Success");
		} catch (SQLException e) {
			System.err.printf("%s", "ERROR: Unable Connect to MySQL");
		}
		return con;
	}
	
	private void loadProperties() {
		Properties prop = DBProperties.loadPropertis("dbcon.xml");
		
		driver = prop.getProperty("DRIVER");
		url = prop.getProperty("URL");
		user = prop.getProperty("USER");
		password = prop.getProperty("PASSWORD");
		
	}
}
